package com.wgg.common.codec;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.jboss.marshalling.ByteInput;
import org.jboss.marshalling.ByteOutput;
import org.jboss.marshalling.InputStreamByteInput;
import org.jboss.marshalling.Marshaller;
import org.jboss.marshalling.MarshallerFactory;
import org.jboss.marshalling.Marshalling;
import org.jboss.marshalling.MarshallingConfiguration;
import org.jboss.marshalling.OutputStreamByteOutput;
import org.jboss.marshalling.Unmarshaller;

/**
 * {netty}中使用marshaller进行编解码的, marshaller的{MarshallingEncoder}和{MarshallingDecoder}支持半包处理
 * 本实例仅是序列化功能的演示
 * @author WSH
 */
public class MarshallingSerializer implements Serializer {

	public static MarshallingSerializer INSTANCE = new MarshallingSerializer();
	
	private MarshallingSerializer () {}
	
	@Override
	public Object deserialize(InputStream in) throws IOException, ClassNotFoundException {
		MarshallerFactory marshallerFactory = Marshalling.getProvidedMarshallerFactory("serial");
		MarshallingConfiguration configuration = new MarshallingConfiguration();
		configuration.setVersion(5);
		Unmarshaller unmarshaller = marshallerFactory.createUnmarshaller(configuration);
		try {
			ByteInput input = new InputStreamByteInput(in);
			unmarshaller.start(input);
			return unmarshaller.readObject();
		} finally {
			unmarshaller.finish();
		}
	} 
	
	@Override
	public void serialize(OutputStream out, Object obj) throws IOException {
		MarshallerFactory marshallerFactory = Marshalling.getProvidedMarshallerFactory("serial");
		MarshallingConfiguration configuration = new MarshallingConfiguration();
		configuration.setVersion(5);
		Marshaller marshaller = marshallerFactory.createMarshaller(configuration);
		ByteOutput byteOupt = new OutputStreamByteOutput(out);
		marshaller.start(byteOupt);
		marshaller.writeObject(obj);
		marshaller.finish();
	}
}
